package com.Mayhem.Android;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import com.Mayhem.Android.R;
import com.google.zxing.integration.android.IntentIntegrator;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.opengl.Visibility;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class MayhemActivity extends HomeScreenHandler 
{	
	private class MayhemWebChromeClient extends WebChromeClient
	{
		MayhemActivity activity;
		public MayhemWebChromeClient(MayhemActivity activity)
		{
			this.activity = activity;
		}
		
		public void onProgressChanged(WebView view, int progress) 
		{
		     // Activities and WebViews measure progress with different scales.
		     // The progress meter will automatically disappear when we reach 100%
		     System.out.println(progress);
		     if(progress == 100 && !activity.DidError)
		     {
				TextView tv = (TextView)findViewById(R.id.textViewStatus);
				tv.setText("");
				tv.setVisibility(TextView.INVISIBLE);
				tv.setTextColor(Color.WHITE);
		     }
		 }
	}
	
	private class MayhemWebViewClient extends WebViewClient 
	{
		MayhemActivity activity;
		ProgressBar progressBar;
		TextView textViewStatus;
		WebView webView;
		public MayhemWebViewClient(MayhemActivity activity)
		{
			this.activity = activity;
			progressBar = (ProgressBar) findViewById(R.id.progressbar);
			textViewStatus = (TextView)findViewById(R.id.textViewStatus);
			webView = (WebView) findViewById(R.id.web_engine);
		}
				
		@Override
		public void onPageStarted(android.webkit.WebView view, java.lang.String url, android.graphics.Bitmap favicon)
		{
			if(!activity.DidError)
			{
				System.out.println("onPageStarted: " + url);
				textViewStatus.setText("Connecting...");
				textViewStatus.setVisibility(TextView.VISIBLE);
		    	textViewStatus.setTextColor(Color.GRAY);
		        progressBar.setVisibility(ProgressBar.VISIBLE);
		        new Timer().schedule(new TimerTask() {
					@Override
					public void run() {
						if(webView.getProgress() < 50)
						{
							setError();	  
							webView.stopLoading();
						}
					}
	
				}, 5000);
			}
		}
		
	    @Override
	    public boolean shouldOverrideUrlLoading(WebView view, String urlNewString)
	    {
	    	if(urlNewString.equals("mayhem:error"))
	    	{
		    	setError();
	    		view.loadData("", "text/html", "UTF-*8");
	    	}
	    	else	
	    	{
	    		System.out.println("shouldOverrideUrlLoading: " + urlNewString);
	        	view.loadUrl(urlNewString);
	    	}
	        return true;
	    }
	    
	    public void onPageFinished (WebView view, String url)
	    {
	    	if(!activity.DidError)
	    	{		    	
		    	System.out.println("onPageFinished: " + url);
		    	ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
		        progressBar.setVisibility(ProgressBar.INVISIBLE);
		        
		        activity.setConnectedToCorrectServer();
	    	}
	    }
	    
	    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) 
	    { 
	    	setError();
	    	System.out.println("onReceivedError: " + failingUrl);
	    	
	    	view.loadData("", "text/html", "UTF-*8");
	    }
	    
	    void setError()
	    {
	    	activity.DidError = true;
	    	/*
	    	progressBar.getHandler().post(new Runnable() {
				public void run() {
					progressBar.setVisibility(ProgressBar.INVISIBLE);					
				}
			});

	    	textViewStatus = (TextView)findViewById(R.id.textViewStatus);
	    	textViewStatus.getHandler().post(new Runnable() {
				public void run() {
					textViewStatus.setVisibility(TextView.VISIBLE);
			    	textViewStatus.setText("Error");
			    	textViewStatus.setTextColor(Color.RED);
				}
	    	});
*/
	        new Timer().schedule(new TimerTask() {
				@Override
				public void run() {
					activity.ConnectToServer();
				}
			}, 1000);

	    }
	}
	
	public boolean DidError = false;
	
	String port;
	String address;
	int ipAttempt = 0;
	public static final String PREFS_NAME = "MyPrefsFile";
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
	    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	    	ViewFlipper vf = (ViewFlipper)findViewById(R.id.flipper);
			View v = findViewById(R.id.main_page);
			if(v != vf.getCurrentView())
			{
				address = ((EditText)findViewById(R.id.editTextIP)).getText().toString();
				port = ((EditText)findViewById(R.id.editTextPort)).getText().toString();
				
				SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
				SharedPreferences.Editor editor = settings.edit();
				editor.putString("IP",address);
				editor.putString("Port", port);
				editor.commit();
				
				vf.showPrevious();
				WebView engine = (WebView) findViewById(R.id.web_engine);
				engine.loadUrl("about:blank");
				new Timer().schedule(new TimerTask() {
					@Override
					public void run() {
						ConnectToServer();
					}
				}, 200);

				return true;
			}
	    }
	    else if(keyCode == KeyEvent.KEYCODE_MENU) {
	    	ViewFlipper vf = (ViewFlipper)findViewById(R.id.flipper);
	    	//vf.setAnimation(AnimationUtils.loadAnimation(view.getContext(),R.anim.)
	    	View v = findViewById(R.id.settings_page);
	    	if(v != vf.getCurrentView())
			{
	    		vf.showNext();
	    		return true;	    		
			}
	    }

	    return super.onKeyDown(keyCode, event);
	}
	
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) 
	    {
		    case R.id.Settings:
		    	ViewFlipper vf = (ViewFlipper)findViewById(R.id.flipper);
		    	//vf.setAnimation(AnimationUtils.loadAnimation(view.getContext(),R.anim.)
		    	View v = findViewById(R.id.web_engine);
				if(v == vf.getCurrentView())
				{
					vf.showNext();
				}
		        return true;
		    default:
		        return super.onOptionsItemSelected(item);
	    }
	}
	
	@Override
	public void onPause() {
		super.onResume();
		WebView engine = (WebView) findViewById(R.id.web_engine);
		engine.loadData("", "text/html", "UTF-*8");
	}
	
	@Override
	public void onResume() {
		super.onResume();
    	ConnectToServer();
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.main);
        
        WebView engine = (WebView) findViewById(R.id.web_engine);
        engine.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        engine.setWebViewClient(new MayhemWebViewClient(this));
        engine.setWebChromeClient(new MayhemWebChromeClient(this));
        engine.getSettings().setBuiltInZoomControls(false);
        engine.getSettings().setSupportZoom(false);
        engine.getSettings().setJavaScriptEnabled(true);
        engine.setBackgroundColor(Color.parseColor("#000000"));
        
        ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
        progressBar.setVisibility(ProgressBar.INVISIBLE);
        
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        address = settings.getString("IP",null);
        port = settings.getString("Port", null);
        
        TextView textViewStatus = (TextView)findViewById(R.id.textViewStatus);
        textViewStatus.setTextColor(Color.GRAY);

        
        if(address != null && port != null)
        {
        	((EditText)findViewById(R.id.editTextIP)).setText(address);
			((EditText)findViewById(R.id.editTextPort)).setText(port);
			
        	ConnectToServer();
        }
        else
        {
        	ViewFlipper vf = (ViewFlipper)findViewById(R.id.flipper);
			View v = findViewById(R.id.web_engine);
			if(v == vf.getCurrentView())
			{
				vf.showNext();
			}
        }
    }
    
    public void ConnectToServer()
    {
    	DidError = false;
        Date date = new Date();
        WebView engine = (WebView)findViewById(R.id.web_engine);
        engine.clearCache(true);
        
        String ip = address;
        
        if(address == null)
        	return;
        
        if (address.contains(";"))
        {
            String[] ips = address.split(";");
            if (++ipAttempt > ips.length - 1)
                ipAttempt = 0;

            ip = ips[ipAttempt];
        }
        String url = String.format("http://%s:%s/Mayhem/Html?t=%s", ip, port, date.getTime());
        engine.loadUrl(url);
    }
    
    public void setConnectedToCorrectServer()
    {
    	if (address != null && address.contains(";"))
        {
            String[] ips = address.split(";");
            address = ips[ipAttempt];
            ((EditText)findViewById(R.id.editTextIP)).setText(address);
            
            SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.putString("IP",address);
			editor.commit();
        }
    }
    
    public void onButtonAutomaticClicked(View view) {
    	IntentIntegrator.initiateScan(this);
    }
    
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode == RESULT_OK)
        {
			String contents = intent.getStringExtra("SCAN_RESULT");
			   
			String[] separated = contents.split(":");
			port = separated[0];
			if(separated.length > 2)
			{
				String ipText = separated[1];
				for (int i = 2; i < separated.length; i++)
                {
                    ipText += ";" + separated[i];
                }
				address = ipText;
			}
			else	
			{
				address = separated[1];
			}
			
			((EditText)findViewById(R.id.editTextIP)).setText(address);
			((EditText)findViewById(R.id.editTextPort)).setText(port);
			
			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.putString("IP",address);
			editor.putString("Port", port);
			editor.commit();
			
			ConnectToServer();
			   
			ViewFlipper vf = (ViewFlipper)findViewById(R.id.flipper);
			View v = findViewById(R.id.web_engine);
			if(v != vf.getCurrentView())
			{
				vf.showPrevious();
			}
			// Handle successful scan
           } else if (resultCode == RESULT_CANCELED) {
               // Handle cancel
       }
   }
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
	    super.onConfigurationChanged(newConfig);
	}
	
	@Override 
	public void onDestroy() {
		super.onDestroy();
		UIHelper.killApp(true);
	}
}